#!/bin/bash
set -x

# set your AWS identifiers
AWS_ACCES_KEY="XXXXXXXXXX"
AWS_SECRET_ACCES_KEY="XXXXXXXXXXXXXXXXXXXXXXXXX"

# create a bucket on s3 and copy your amazon certificate and private key
# named ac cert.pem and pk.pem
S3_BUCKET=aarf-tutorial

export S3_ACCESS_KEY_ID=$AWS_ACCES_KEY
export S3_SECRET_ACCESS_KEY=~/.ec2/key
echo -n $AWS_SECRET_ACCES_KEY > ~/.ec2/key

export JAVA_HOME=/apps/jdk1.5.0_19
export EC2_PRIVATE_KEY=~/.ec2/pk.pem
export EC2_CERT=~/.ec2/cert.pem

export AWS_ELB_HOME=/apps/ElasticLoadBalancing-1.0.1.23
export AWS_CLOUDWATCH_HOME=/apps/CloudWatch-1.0.0.22
export AWS_AUTO_SCALING_HOME=/apps/AutoScaling-1.0.4.4
export EC2_HOME=/apps/ec2-api-tools-1.3-36506

export PATH=$PATH:/apps/bin:$JAVA_HOME/bin:$EC2_HOME/bin:$AWS_AUTO_SCALING_HOME/bin:$AWS_ELB_HOME/bin:$AWS_CLOUDWATCH_HOME/bin

cd ~/.ec2
s3 get $S3_BUCKET cert.pem
s3 get $S3_BUCKET pk.pem
cd ~
s3 get $S3_BUCKET wadi_first.xml
s3 get $S3_BUCKET wadi_template.xml

as-describe-auto-scaling-groups  jetty-group --delimiter "|" > ~/auto-scaling-groups.log
ec2-describe-instances > ~/instances.log

cd /apps/jetty-6.1
rm /apps/jetty-6.1/contexts/wadi*.xml

MY_ID=$(wget -qO - http://169.254.169.254/latest/meta-data/instance-id)
echo $MY_ID > ~/my_id.log
NODE=$MY_ID

if [ $(grep INSTANCE ~/auto-scaling-groups.log|wc -l) -eq 1 ]; then 
  ###############
  # first node needs no reference to other static memmbers
  ###############
  cp ~/wadi_first.xml /apps/jetty-6.1/contexts/
else 
  ###############
  # Begining of the wadi.xml
  ###############
  sed -n "1,/-- STATIC MEMBERS BEGIN --/ p" ~/wadi_template.xml > ~/wadi.xml

  OTHERS=$(grep INSTANCE ~/auto-scaling-groups.log|grep -v $MY_ID|cut -d "|" -f 2|sed -n "H;$ {x;s/\n/ /gp}")
  for i in $OTHERS
  do
    NEXT_INTERNAL_DNS=$(grep $i  ~/instances.log |sed "s/.*ip-\([^ ]*\).ec2.internal.*/\1/")
    NEXT_HOST=$(echo $NEXT_INTERNAL_DNS|tr "-" ".")
    NEXT_UNIQ_ID=$(for i in $(echo $NEXT_INTERNAL_DNS|tr "-" " "); do echo -n ",$((i-127))"; done)
    echo  "$i => $NEXT_INTERNAL_DNS => NEXT_HOST=$NEXT_HOST => NEXT_PADDED_HOST=$NEXT_PADDED_HOST => NEXT_UNIQ_ID=$NEXT_UNIQ_ID"

    cat >>  ~/wadi.xml <<END-OF-INPUT
    <Call name="addStaticMember">
      <Arg>
            <New class="org.apache.catalina.tribes.membership.StaticMember">
                <Set name="Host">$NEXT_HOST</Set>
                <Set name="Port">4000</Set>
                <Set name="UniqueId">{0,0,0,0,0,0,0,0,0,0,0,0${NEXT_UNIQ_ID}}</Set>
            </New>
      </Arg>
    </Call>
END-OF-INPUT

  done
  ###############
  # the end of wadi.xml
  ###############
  sed -n "/-- STATIC MEMBERS END --/,$ p" ~/wadi_template.xml >> ~/wadi.xml

  cp ~/wadi.xml /apps/jetty-6.1/contexts/wadi_static_members.xml
fi

echo $NODE > /apps/jetty-6.1/webapps/test/node.jsp
java -Dnode.name=$NODE -jar start.jar &> /root/jetty.log &
